package com.xyzm.mytest.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;

/**
 *
 */
public class TestNonBlockingNIO {
    @Test
    public void client() throws IOException {
        //1、获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        //2、切换非阻塞模式
        socketChannel.configureBlocking(false);
        //3、分配指定大小的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //4、发送数据给服务端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String next = scanner.next();
            byteBuffer.put((new Date().toString()+":\t"+next).getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        //5、关闭通道
        socketChannel.close();
    }

    @Test
    public void server() throws IOException {
        //1、获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2、设置非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //3、绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9898));
        //4、获取选择器
        Selector selector = Selector.open();
        //5、将通道注册到选择器上，并指定监听事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //6、轮询式的获取选择器上已就绪的事件
        while (selector.select()>0){
            //7、获取当前选择器中所有注册的选择键（已就绪的监听事件）
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                //8、获取就绪事件
                SelectionKey selectionKey = iterator.next();
                //9、判断具体是什么时间准备的
                if(selectionKey.isAcceptable()){
                    //10、若”接受就绪“，获取客户端连接
                    SocketChannel accept = serverSocketChannel.accept();
                    //11、切换非阻塞模式
                    accept.configureBlocking(false);
                    //12、将该通道注册到选择器上
                    accept.register(selector,SelectionKey.OP_READ);
                }else if (selectionKey.isReadable()){
                    //13、获取当前选择器上的”读就绪“状态的通道
                    SocketChannel readChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    //14、读取数据
                    int len = 0;
                    while ((len = readChannel.read(byteBuffer))!=-1){
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(),0,len));
                        byteBuffer.clear();
                    }
                }
                //15、取消选择键SelectorKey
                iterator.remove();
            }

        }
    }
}
